package com.school.campus.task;

import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.school.campus.domain.Activity;
import com.school.campus.service.IActivityService;
import com.school.campus.service.redis.ActivityRedisService;

/**
 * 活动状态自动更新任务
 * 定时检查活动时间并自动更新活动状态
 */
@Component
public class ActivityStatusTask {

    @Autowired
    private IActivityService activityService;

    @Autowired
    private ActivityRedisService activityRedisService;

    /**
     * 检查并更新活动状态
     * 根据当前时间与活动开始、结束时间的比较自动更新活动状态
     */
    public void checkAndUpdateActivityStatus() {
        // 1. 首先检查并处理Redis中的过期提醒
        activityRedisService.checkAndProcessExpiredReminders();

        // 2. 获取当前时间
        Date now = new Date();

        // 3. 创建查询条件，只查询已发布(1)和进行中(2)的活动
        Activity query = new Activity();

        // 4. 查询所有需要检查状态的活动
        List<Activity> activities = activityService.selectActivityList(query);

        for (Activity activity : activities) {
            // 跳过草稿和已取消的活动
            if (activity.getActivityStatus() == 0 || activity.getActivityStatus() == 4) {
                continue;
            }

            boolean statusChanged = false;
            Long newStatus = activity.getActivityStatus();

            // 检查是否应该更新为进行中
            if (activity.getActivityStatus() == 1 &&
                    activity.getStartTime() != null &&
                    now.after(activity.getStartTime())) {
                newStatus = 2L;
                statusChanged = true;
            }

            // 检查是否应该更新为已结束
            if ((activity.getActivityStatus() == 1 || activity.getActivityStatus() == 2) &&
                    activity.getEndTime() != null &&
                    now.after(activity.getEndTime())) {
                newStatus = 3L;
                statusChanged = true;
            }

            // 如果状态发生变化，更新状态并更新缓存
            if (statusChanged) {
                activityService.dealWithActivity(activity.getId(), newStatus);

                // 更新活动状态
                activity.setActivityStatus(newStatus);

                // 更新Redis缓存
                activityRedisService.cacheActivity(activity);
            } else if (activity.getActivityStatus() == 1) {
                // 如果活动尚未开始，设置Redis提醒
                activityRedisService.setActivityStartReminder(activity);
                activityRedisService.setActivityEndReminder(activity);
            }
        }
    }
}